// ImageGridAdapter.kt
package com.example.myapplication.picUtils

import android.content.Context
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.CheckBox
import android.widget.GridView
import android.widget.ImageView
import coil.load
import com.example.myapplication.R

// 定义一个接口，让 Activity 处理拍照按钮的点击
interface OnCameraIconClickListener {
    fun onCameraIconClick()
}

class ImageGridAdapter(
    private val context: Context,
    private var images: MutableList<ImageItem>,
    private val selectedImages: MutableList<ImageItem>,
    private val maxSelection: Int,
    private val showCameraButton: Boolean, // 新增：是否显示拍照按钮
    private val onSelectionChanged: (ImageItem, Boolean) -> Unit,
    private val onCameraClickListener: OnCameraIconClickListener? = null // 新增：拍照按钮点击回调
) : BaseAdapter() {

    private val VIEW_TYPE_IMAGE = 0
    private val VIEW_TYPE_CAMERA = 1

    override fun getViewTypeCount(): Int = 2 // 图片项 + 拍照项

    override fun getItemViewType(position: Int): Int {
        return if (showCameraButton && position == 0) VIEW_TYPE_CAMERA else VIEW_TYPE_IMAGE
    }

    override fun getCount(): Int = if (showCameraButton) images.size + 1 else images.size

    override fun getItem(position: Int): ImageItem? { // 注意：拍照项没有 ImageItem
        return if (showCameraButton) {
            if (position == 0) null else images[position - 1]
        } else {
            images[position]
        }
    }

    override fun getItemId(position: Int): Long {
        return if (showCameraButton && position == 0) {
            -1L // 拍照项的特殊ID
        } else {
            getItem(position)?.id ?: position.toLong()
        }
    }
    // 添加一个方法来获取当前的图片列表 (不包括相机图标)
    fun getImages(): List<ImageItem> {
        return images.toList() // 返回副本
    }




    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        val viewType = getItemViewType(position)
        var currentView = convertView

        if (viewType == VIEW_TYPE_CAMERA) {
            if (currentView == null) {
                currentView = LayoutInflater.from(context).inflate(R.layout.item_image_picker_camera, parent, false) // 你需要创建这个拍照项的布局
                currentView.tag = CameraViewHolder(currentView) // 如果拍照项有特定 ViewHolder
            }
            // (currentView?.tag as? CameraViewHolder)?.bind() // 如果需要绑定数据或监听
            currentView?.setOnClickListener {
                onCameraClickListener?.onCameraIconClick()
            }
            // 动态设置拍照项高度与父容器（GridView的列宽）一致，使其为正方形
            currentView?.post {
                val width = (parent as? GridView)?.columnWidth ?: currentView!!.width // 获取列宽或自身宽度
                if (width > 0 && currentView!!.layoutParams.height != width) {
                    currentView!!.layoutParams.height = width
                    currentView!!.requestLayout()
                }
            }
        } else { // VIEW_TYPE_IMAGE
            val imageViewHolder: ImageViewHolder
            if (currentView == null || currentView.tag !is ImageViewHolder) { // 确保是正确的 ViewHolder 类型
                currentView = LayoutInflater.from(context).inflate(R.layout.item_image_picker_grid, parent, false)
                imageViewHolder = ImageViewHolder(currentView)
                currentView.tag = imageViewHolder
            } else {
                imageViewHolder = currentView.tag as ImageViewHolder
            }

            val imageItem = getItem(position) // 对于图片项，这里不会为 null
            imageItem?.let { item ->
                item.isSelected = selectedImages.any { it.id == item.id }

                imageViewHolder.imageView.load(item.uri) {
                    placeholder(R.drawable.ic_launcher_background)
                    error(R.drawable.ic_launcher_background)
                }
                imageViewHolder.checkBox.isChecked = item.isSelected

                imageViewHolder.checkBox.setOnClickListener {
                    val isChecked = imageViewHolder.checkBox.isChecked
                    if (isChecked && selectedImages.size >= maxSelection && !selectedImages.any { it.id == item.id }) {
                        imageViewHolder.checkBox.isChecked = false
                    } else {
                        item.isSelected = isChecked
                        onSelectionChanged(item, isChecked)
                    }
                }

                currentView?.setOnClickListener {
                    imageViewHolder.checkBox.performClick()
                }

                if (selectedImages.size >= maxSelection && !item.isSelected) {
                    imageViewHolder.itemView.alpha = 0.5f
                } else {
                    imageViewHolder.itemView.alpha = 1.0f
                }

                // 动态设置图片项高度，使其为正方形
                imageViewHolder.imageView.post {
                    val width = imageViewHolder.imageView.width
                    if (width > 0 && imageViewHolder.imageView.layoutParams.height != width) {
                        imageViewHolder.imageView.layoutParams.height = width
                        imageViewHolder.imageView.requestLayout()
                    }
                }
            }
        }
        return currentView!!
    }

    fun updateImages(newImages: List<ImageItem>) {
        images.clear()
        images.addAll(newImages)
        Log.d("ImageGridAdapter", "更新图片，新数量: ${images.size}")
        notifyDataSetChanged()
    }

    // 图片项的 ViewHolder
    private class ImageViewHolder(val itemView: View) {
        val imageView: ImageView = itemView.findViewById(R.id.iv_grid_image)
        val checkBox: CheckBox = itemView.findViewById(R.id.cb_image_select)
    }

    // 拍照项的 ViewHolder (可选，如果布局简单可以不用)
    private class CameraViewHolder(val itemView: View) {
        // val cameraIcon: ImageView = itemView.findViewById(R.id.iv_camera_icon) // 假设拍照项布局中有个图标
    }
}
